import os
import sys
import subprocess
import logging
from config import config

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def setup_logging():
    """设置日志配置"""
    # 获取当前环境，默认为development
    env = os.environ.get('FLASK_ENV', 'development')
    log_level = getattr(logging, config[env].LOG_LEVEL)
    logging.basicConfig(
        level=log_level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(config[env].LOG_FILE, encoding='utf-8'),
            logging.StreamHandler(sys.stdout)
        ]
    )

def check_dependencies():
    """检查依赖是否安装"""
    try:
        import flask
        import moviepy
        import requests
        return True
    except ImportError as e:
        print(f"缺少依赖包: {e}")
        return False

def create_directories():
    """创建必要的目录"""
    # 获取当前环境，默认为development
    env = os.environ.get('FLASK_ENV', 'development')
    os.makedirs(config[env].TEMP_DIR, exist_ok=True)
    os.makedirs(config[env].OUTPUT_DIR, exist_ok=True)

def main():
    """主函数"""
    # 设置日志
    setup_logging()
    
    # 检查依赖
    if not check_dependencies():
        print("请先安装依赖: pip install -r requirements.txt")
        sys.exit(1)
    
    # 创建必要目录
    create_directories()
    
    # 尝试使用waitress启动生产级服务器
    try:
        from waitress import serve
        from app import app
        print("使用 Waitress 启动生产级服务器...")
        serve(app, host='0.0.0.0', port=5000)
    except ImportError:
        # 如果没有安装waitress，回退到Flask内置服务器（仅用于开发）
        print("未安装 Waitress，回退到 Flask 内置服务器（仅用于开发）...")
        from app import app
        app.run(
            host='0.0.0.0',
            port=5000,
            debug=False,
            threaded=True
        )

if __name__ == '__main__':
    main()